package com.fun.feifun.modules.business.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fun.feifun.base.utils.common.ListUtil;
import com.fun.feifun.modules.business.model.BusinessGoods;
import com.fun.feifun.modules.business.model.BusinessUserGoods;
import com.fun.feifun.modules.business.dao.BusinessUserGoodsMapper;
import com.fun.feifun.modules.business.model.BusinessUserRoute;
import com.fun.feifun.modules.business.model.dto.BusinessAmountRecordDto;
import com.fun.feifun.modules.business.model.dto.BusinessUserGoodsDto;
import com.fun.feifun.modules.business.model.dto.BusinessUserRouteDto;
import com.fun.feifun.modules.business.model.param.BusinessAmountRecordPage;
import com.fun.feifun.modules.business.model.param.BusinessUserGoodsParam;
import com.fun.feifun.modules.business.model.param.BusinessUserParam;
import com.fun.feifun.modules.business.service.IBusinessGoodsService;
import com.fun.feifun.modules.business.service.IBusinessUserGoodsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fun.feifun.modules.business.service.IBusinessUserRouteService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 业务用户商品信息 服务实现类
 * </p>
 *
 * @author wkf
 * @since 2024-05-29
 */
@Service
public class BusinessUserGoodsServiceImpl extends ServiceImpl<BusinessUserGoodsMapper, BusinessUserGoods> implements IBusinessUserGoodsService {


    @Resource
    private IBusinessGoodsService goodsService;

    @Resource
    private IBusinessUserRouteService userRouteService;

    @Override
    public List<BusinessUserGoodsDto> getUserDtoPage(BusinessUserParam page) {
        QueryWrapper<BusinessUserRoute> queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda().eq(BusinessUserRoute::getUserId,page.getUserId());
        List<BusinessUserRoute> routes = userRouteService.list(queryWrapper);
        Map<Long, List<BusinessUserRoute>> routeMap = routes.stream().collect(Collectors.groupingBy(it -> it.getGoodsId()));
        List<BusinessUserGoodsDto> list = baseMapper.selectUserDtoList(page);
        list.forEach(it->{
            List<BusinessUserRoute> businessUserRoutes = routeMap.get(it.getGoodsId());
            if(!CollectionUtils.isEmpty(businessUserRoutes)){
                List<BusinessUserRouteDto> collect = businessUserRoutes.stream().map(item -> item.toDto()).collect(Collectors.toList());
                it.setRoutes(collect);
            }else{
                it.setRoutes(new ArrayList<>());
            }
        });
        return list;
    }

    @Override
    public List<BusinessUserGoodsDto> getSupplierDtoPage(BusinessUserParam page) {
        List<BusinessUserGoodsDto> list = baseMapper.selectSupplierDtoList(page);
        return list;
    }

    public Boolean saveUserGoods(BusinessUserGoodsParam param) {
        List<BusinessUserGoods> list=new ArrayList<>();
        List<BusinessUserRoute> routeList=new ArrayList<>();

        Long userId = param.getUserId();
        List<BusinessUserGoodsParam.GoodsFees> goodsList = param.getGoodsList();

        //获取商品
        List<Long> goodsIds = goodsList.stream().map(it -> it.getGoodsId()).collect(Collectors.toList());
        QueryWrapper<BusinessGoods> goodsWrapper=new QueryWrapper<>();
        goodsWrapper.lambda().in(BusinessGoods::getId,goodsIds);
        List<BusinessGoods> goodss = goodsService.list(goodsWrapper);
        Map<Long, BusinessGoods> goodsMap =new HashMap<>();
        if(!ListUtil.isEmpty(goodss)){
            goodsMap=goodsService.list(goodsWrapper).stream().collect(Collectors.toMap(BusinessGoods::getId, goods -> goods));
        }
        //组装商品用户关联对象。
        for (BusinessUserGoodsParam.GoodsFees goodsFees:goodsList) {
            BusinessUserGoods userGoods=new BusinessUserGoods();
            userGoods.setId(goodsFees.getId());
            userGoods.setUserId(userId);
            userGoods.setGoodsId(goodsFees.getGoodsId());
            userGoods.setFeesAmount(goodsFees.getFeesAmount());
            userGoods.setHasAuthor(goodsFees.isHasAuthor());
            BusinessGoods goods = goodsMap.get(goodsFees.getGoodsId());
            if(ObjectUtils.isEmpty(goods)){
                userGoods.setTotalAmount(goods.getAmount().add(goodsFees.getFeesAmount()));
                userGoods.setGoodsAmount(goods.getAmount());
            }
            for (int i=0;i<goodsFees.getRoutes().size();i++){
                BusinessUserRouteDto dto = goodsFees.getRoutes().get(i);
                BusinessUserRoute route=new BusinessUserRoute();
                route.setGoodsId(goodsFees.getGoodsId());
                route.setUserId(userId);
                route.setSupplierId(dto.getSupplierId());
                route.setContactName(dto.getContactName());
                route.setPriorityLevel(i);
                routeList.add(route);
            }
            list.add(userGoods);
        }
        //删除这个人下面没拥有的数据
        List<Long> ids = goodsList.stream().map(it -> it.getId()).collect(Collectors.toList());
        QueryWrapper<BusinessUserGoods> userGoodsWrapper=new QueryWrapper<>();
        userGoodsWrapper.lambda().eq(BusinessUserGoods::getUserId,param.getUserId()).notIn(BusinessUserGoods::getId,ids);
        remove(userGoodsWrapper);
        userRouteService.remove(new QueryWrapper<BusinessUserRoute>().lambda().eq(BusinessUserRoute::getUserId, userId));
        userRouteService.saveOrUpdateBatch(routeList);
        return saveOrUpdateBatch(list);
    }

    @Override
    public Map<Long, Long> getUserGoodsCount(List<Long> usreIds) {
        List<Map<String, Long>> list = this.baseMapper.getUserGoodsCount(usreIds);
        Map<Long, Long> userGoodsCount =new HashMap<>();
        list.forEach(item->{
            userGoodsCount.put(item.get("userId"),item.get("count"));
        });
        return userGoodsCount;
    }



}
